import request from '@/utils/request'
import { storage } from '@/utils/Storage'
import { defineStore } from 'pinia'
let storeDict = storage.get('DICT-LIST') || []
const useDictStore = defineStore('dict', {
  state: () => ({
    dict: storeDict
  }),
  getters: {
    dictList: state => {
      return dictName => state.dict.filter(v => v.dictType == dictName)
    }
  },
  actions: {
    // 获取字典
    getDict (_key) {
      if (_key == null && _key == '') {
        return null
      }
      try {
        for (let i = 0; i < this.dict.length; i++) {
          if (this.dict[i].key == _key) {
            return this.dict[i].value
          }
        }
      } catch (e) {
        return null
      }
    },
    getAllDictList () {
      return new Promise((resolve, reject) => {
        // request({ url: '/business/stu/queryDict' })
        request({ url: '/system/dict/data/selectDictDataAll' })
          .then(res => {
            if (res.code == 200) {
              this.dict = res.data || []
              storage.set(DCITLIST, res.rows)
            }
            resolve(res)
          })
          .catch(error => {
            reject(error)
          })
      })
    },
    // 设置字典
    setDict (_key, value) {
      if (_key !== null && _key !== '') {
        this.dict.push({
          key: _key,
          value: value
        })
      }
    },
    // 删除字典
    removeDict (_key) {
      var bln = false
      try {
        for (let i = 0; i < this.dict.length; i++) {
          if (this.dict[i].key == _key) {
            this.dict.splice(i, 1)
            return true
          }
        }
      } catch (e) {
        bln = false
      }
      return bln
    },
    // 清空字典
    cleanDict () {
      this.dict = new Array()
    },
    // 初始字典
    initDict () {}
  }
})

export default useDictStore
